﻿using Gumini.JulaDB.Provider;
using Gumini.JulaDB.Test.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Gumini.JulaDB.Test
{
    /// <summary>
    /// Class containing tests for the SQL DELETE statement.
    /// </summary>
    [TestClass]
    public class DeleteTest
    {
        private static JulaDbConnection _connection;
        private static PersonTestDataCreator _peopleData;

        [TestInitialize]
        public void InitializeTest()
        {
            // database is initialized before every test to discard any changes made by previous tests
            _connection = TestUtils.CreateTestDatabase();
            _peopleData = new PersonTestDataCreator(_connection);
        }

        [TestCleanup]
        public void CleanupTest()
        {
            _connection.Close();
        }

        /// <summary>
        /// Delete one row with a given id.
        /// </summary>
        [TestMethod]
        public void DeleteSingleRow()
        {
            _connection.ExecuteValidScalar(@"select count(*) from person where id = 2", 1);

            int rowsAffected = _connection.ExecuteValidNonQuery(@"delete from person where id = 2");
            Assert.AreEqual(1, rowsAffected);

            _connection.ExecuteValidScalar(@"select count(*) from person where id = 2", 0);
        }

        /// <summary>
        /// Delete the rows that match a condition.
        /// </summary>
        [TestMethod]
        public void DeleteTwoRows()
        {
            _connection.ExecuteValidScalar(@"select count(*) from person where firstname = 'Jan'", 2);

            int rowsAffected = _connection.ExecuteValidNonQuery(@"delete from person where firstname = 'Jan'");
            Assert.AreEqual(2, rowsAffected);

            _connection.ExecuteValidScalar(@"select count(*) from person where firstname = 'Jan'", 0);
        }

        /// <summary>
        /// Delete all rows (no WHERE condition).
        /// </summary>
        [TestMethod]
        public void DeleteAllRows()
        {
            int rowsAffected = _connection.ExecuteValidNonQuery(@"delete from person");
            Assert.AreEqual(_peopleData.TotalPersonCount, rowsAffected);

            _connection.ExecuteValidScalar(@"select count(*) from person", 0);
        }
    }
}
